package com.itheima.csdn_hongchen.controller;

import com.itheima.csdn_hongchen.method.DbConn;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.itheima.csdn_hongchen.method.DbConn.GetConn;

@RestController
@RequestMapping("/api")
public class DataController {

    @PostMapping("/insert")
    public Map<String, String> insertData(@RequestBody Map<String, String> requestData) throws SQLException {
        String itemName = requestData.get("itemName");
        String value = requestData.get("value");
        DbConn.InsertData(itemName, value);
        Map<String, String> response = new HashMap<>();
        response.put("message", "添加成功");
        return response;
    }

    @GetMapping("/data")
    public List<Map<String, String>> fetchData() {
        List<Map<String, String>> dataList = new ArrayList<>();
        try {
            Connection conn = GetConn();
            String sql="SELECT * FROM first_table ";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                Map<String, String> data = new HashMap<>();
                data.put("id", rs.getString("id"));
                data.put("itemName", rs.getString("item_name"));
                data.put("value", rs.getString("Value"));
                dataList.add(data);
            }
        } catch (SQLException e) {
            throw new RuntimeException("Error fetching data", e);
        }
        return dataList;
    }

    @PutMapping("/update/{id}")
    public Map<String, String> updateData(@PathVariable int id, @RequestBody Map<String, String> requestData) throws SQLException {
        String value = requestData.get("value");
        DbConn.updateData(id, value);
        Map<String, String> response = new HashMap<>();
        response.put("message", "修改成功");
        return response;
    }

    @DeleteMapping("/delete/{id}")
    public Map<String, String> deleteData(@PathVariable int id) throws SQLException {
        DbConn.deleteData(id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "删除成功");
        return response;
    }
}
